<template>
  <div>
    <el-dialog
      title="退房"
      :visible.sync="FormVisible"
      width="500px"
      lock-scroll
      v-loading="loading"
      :destroy-on-close="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      @open="onOpen"
      @close="onClose"
    >
      <div class="win-warp" style="height: 300px">
        <el-row :gutter="12">
          <el-form
            ref="elForm"
            :model="formData"
            :rules="rules"
            size="small"
            label-width="80px"
          >
            <el-col :span="24">
              <el-form-item label="退宿原因" prop="checkOutReason">
                <el-select
                  v-model="formData.checkOutReason"
                  placeholder="请选择退宿原因"
                  clearable
                  filterable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in roomOutList"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="退宿日期" prop="handleTime">
                <el-date-picker
                  v-model="formData.handleTime"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{ width: '100%' }"
                  placeholder="请选择退宿日期"
                  clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预留床位" prop="ifOverseas">
                <el-radio-group v-model="formData.reserve">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  placeholder="请输入备注"
                  maxlength="200"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="文件上传">
                <el-upload
                  :limit="limitNum"
                  action="/api/file/upload"
                  accept=".xls, .xlsx, .jpeg, .jpg, .png, .gif, .bmp, .doc, .docx"
                  :data="Imgdata"
                  :headers="headers"
                  :before-upload="beforeUploadFile"
                  :on-change="fileChange"
                  :on-exceed="exceedFile"
                  :on-success="handleSuccess"
                  :on-remove="handRemove"
                  :on-error="handleError"
                  :file-list="fileList"
                  :on-preview="preview"
                >
                  <el-button size="small" type="primary">立即上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm" :loading="btnLoading"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { apiIndex } from "@/api/accommodation/index";
import { download } from "@/itsoftUI/utils/download";
import Token from "@/itsoftUI/auth/token.js";
import { isNumber } from "@/itsoftUI/utils/validate";
import { getPremission } from "@/itsoftUI/auth/permission";
import { dictDataApi } from "@/api/basicData/dataDictionary";
export default {
  inheritAttrs: false,
  components: {},
  props: [],
  data() {
    return {
      loading: false,
      FormVisible: false,
      btnLoading: false,
      headers: {
        Token: "",
        TokenKey: "",
      },

      limitNum: 6,
      Imgdata: { system: "apartment" },
      fileList: [], // excel文件列表
      fileVOS: [],
      roomOutList: [],
      formData: {
        checkOutReason: "",
        handleTime: this.getNowTime(),
        remark: "",
        reserve: "0",
      },
      rules: {
        checkOutReason: [
          {
            required: true,
            message: "请选择退宿原因",
            trigger: "change",
          },
        ],
        handleTime: [
          {
            required: true,
            message: "请选择退宿日期",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "请填写备注",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {},
  watch: {
    toolButtons: {
      handler: function (val) {
        let that = this;
        // 入住办理
        let rShen = val.filter((item) => item.auth === "030103");
        if (rShen && rShen.length > 0 && rShen[0].disabled)
          that.liveAudit = false;
      },
      deep: true,
    },
  },
  created() {
    this.funRoomOut();
  },
  mounted() {},
  methods: {
    preview(file) {
      if (file.path != undefined) {
        download(this.$itsoftUI.config.fileServer + "/" + file.path, file.name);
      } else {
        download(
          this.$itsoftUI.config.fileServer + file.response.data.path,
          file.name
        );
      }
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(
        `只能选择 ${this.limitNum} 个文件，当前共选择了 ${
          files.length + fileList.length
        } 个`
      );
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {},
    handRemove(file, fileList) {
      if (file.response) {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].path == file.response.data.path) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].path == file.path) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      }
      if (file.response) {
        for (var i = 0; i < this.fileVOS.length; i++) {
          if (this.fileVOS[i].path == file.response.data.path) {
            this.fileVOS.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.fileVOS.length; i++) {
          if (file.path.indexOf(this.fileVOS[i].path) != -1) {
            this.fileVOS.splice(i, 1);
            break;
          }
        }
      }
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      this.headers.Token = Token.getToken();
      this.headers.TokenKey = Token.getTokenKey();
      this.btnLoading = true;
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.fileVOS.push(res.data);
      this.$message.success("文件上传成功");
      this.btnLoading = false;
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
      this.btnLoading = false;
    },
    //证件类型
    funRoomOut() {
      let condition = [
        {
          andOr: "and",
          searchField: "dictionaryId",
          operator: "=",
          searchValue: "tsyy",
        },
      ];
      dictDataApi.dictRightList(JSON.stringify(condition)).then((res) => {
        if (res.errorCode === 0) {
          this.roomOutList = res.data;
        }
      });
    },
    //处理默认选中当前日期
    getNowTime() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      var date = now.getDate(); //得到日期
      var hour = " 00:00:00"; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      var defaultDate = `${year}-${month}-${date}${hour}`;
      return defaultDate;
    },
    closeDia() {
      this.$emit("closeDia");
    },
    clearSet() {
      this.$emit("clearSet");
    },
    onOpen() {},
    onClose() {
      this.formData = {
        checkOutReason: "",
        handleTime: this.getNowTime(),
        roomRemark: "",
        reserve: "0",
      };
      this.fileList = [];
      this.fileVOS = [];
      this.clearSet();
      //   this.$refs["elForm"].resetFields();
    },
    close() {
      this.FormVisible = false;
    },
    handelConfirm() {
      this.loading = true;
      let nameList = [];
      let pathList = [];

      this.fileVOS.forEach((el) => {
        nameList.push(el.name);
        pathList.push(el.path);
      });
      this.formData.fileUrl = pathList.toString();
      this.formData.fileName = nameList.toString();
      // bedsId, checkOutReason, handleTime, reserve, studentId, fileName, fileUrl

      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          apiIndex
            .ConfirmCheckout(
              this.formData.bedsId,
              this.formData.checkOutReason,
              this.formData.handleTime,
              this.formData.reserve,
              this.formData.studentId,
              this.formData.fileName,
              this.formData.fileUrl
            )
            .then((res) => {
              if (res.status == "success") {
                this.$message.success("退宿成功");
                this.FormVisible = false;
                this.loading = false;
                this.clearSet();
                this.closeDia();
              }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          this.loading = false;
        }
      });
    },
  },
};
</script>
<style>
</style>
